""" System imports """
import os,sys
import logging

""" Other modules """
import pygame
from pygame.locals import *

""" Game """

""" Set up logging """
_log = logging.getLogger("epicquest.ui.font")
_log.debug("Initializing Font")

class Font(object):
    
    def __init__(self, font, color=(255, 255, 255)):
        
        self.scale = 1
        
        #Dict to hold the letter images
        self.letters = {}
        
        import os
        letters = {}
        format = " abcdefghijklmnopqrstuvwxyz0123456789-+:,.=!)(?><"
        i = 0
        self.font = font
        self.color = color
        strip = pygame.image.load(os.path.dirname(__file__) + \
            "/" + self.font["file"]).convert_alpha()
        for x in range(len(format)):
            letters[format[i]] = pygame.Surface(self.font["size"])
            letters[format[i]].blit(strip, (-x*self.font["size"][0], 0))
            i += 1
        
        #Create the letters
        for letter in letters:
            x = 0
            y = 0
            letterimg = letters[letter]
            self.letters[letter] = pygame.Surface(self.font["size"])
            self.letters[letter].set_colorkey((0, 0, 0), RLEACCEL)
            for y in range(letterimg.get_height()):
                for x in range(letterimg.get_width()):
                    if letterimg.get_at((x, y)) == (255, 255, 255, 255):
                        self.letters[letter].set_at(
                            (x, y), color
                            )
                    x += 1
                y += 1
                x = 0
    
    def render(self, text):
        text = text.lower()
        img = pygame.Surface((len(text)*self.font["size"][0], 
            self.font["size"][1]))
        img.set_colorkey((0, 0, 0), RLEACCEL)
        pos = 0
        for char in text:
            if char in self.letters:
                img.blit(self.letters[char], (pos, 0))
            pos += self.font["size"][0]
        img = pygame.transform.smoothscale(img, (img.get_width() * self.scale, img.get_height() * self.scale))
        return img
    
    
    def render_center(self, text, surface, h_loc = False, v_loc = False):
        surf = self.render(text)
        
        if h_loc is False:
            h_loc = (surface.get_width() - surf.get_width()) / 2
        if v_loc is False:
            v_loc = (surface.get_height() - surf.get_height()) / 2
            
        surface.blit(surf, (h_loc, v_loc))
        return surf
        
    def get_width(self):
        return self.font["size"][0]

    def get_height(self):
        return self.font["size"][1]
    
    def get_pixel_width(self, text):
        return self.get_width() * text.length

    def get_pixel_height(self, text):
        return self.get_height()
    
    def get_scale(self):
        return self.scale
    
    def set_scale(self, scale = 1.0):
        self.scale = scale
